"""Handles the MYSQL DB interface and provides some useful SNOMED-related
functions"""

import MySQLdb
from sets import Set

def sql_connect():
    try:
        connection = MySQLdb.connect(host="Localhost",
                                     user="root", passwd="root",
                                     db="")
        #connection = MySQLdb.connect(host="129.78.9.253",
        #                             user="clinnote", passwd="clinical",
        #                             db="clinnote" )
        #print 'connected'
        return connection

    except MySQLdb.OperationalError, message:
        errorMessage = "Error %d:\n%s" % (message[ 0 ], message[ 1 ] )
        print "Content-Type: text/plain\r\n\r\n"
        print errorMessage
        
connection = sql_connect()
connection.autocommit(False)
            
#connection_snomed = sql_connect("snomed")
#connection_hosrep = sql_connect("hosrep")
#connection_snomed.autocommit(False)
#connection_hosrep.autocommit(False)

#ROOT_ID = 138875005

#def id_ancestors(id):
#    cursor = connection_snomed.cursor()
#    sql = """select CONCEPT_ID_2, FSN
#             from ISA_RELATIONSHIPS, CONCEPTS
#             where CONCEPT_ID = CONCEPT_ID_2
#             and CONCEPT_ID_1 = %d"""
#    while id != ROOT_ID:
#        if not cursor.execute(sql % id):
#            break
#        id, nm = cursor.fetchone()
#        yield id, nm
#    cursor.close()
#
#def active_status(st):
#    if st in [0, 6, 11]:
#        return True
#    return False
#
#def desc_concepts(dids, rem_inactive=True):
#    sql = """select D.CONCEPT_ID, C.CONCEPT_STATUS
#             from DESCRIPTIONS as D, CONCEPTS as C
#             where D.CONCEPT_ID = C.CONCEPT_ID
#               and D.DESCRIPTION_ID IN ('%s')""" % ', '.join([str(id) for id in dids])
#    cursor = connection_snomed.cursor()
#    cursor.execute(sql)
#    res = Set()
#    for id, st in cursor.fetchall():  # should remove fetchall()
#        if rem_inactive and not active_status(st):
#            continue
#        res.add(id)
#    cursor.close()
#    return res
#
#def concept_fsns(ids):
#    if not ids:
#        return {}
#    sql = "select CONCEPT_ID, FSN from CONCEPTS where CONCEPT_ID in (%s)" % (', '.join([str(id) for id in ids]))
#    res = {}
#    cursor = connection_snomed.cursor()
#    cursor.execute(sql)
#    for cid, fsn in cursor.fetchall():   # should remove fetchall()
#        res[cid] = fsn
#    cursor.close()
#    return res
#
#def conceptFSN(conceptId):
#    sql = "select CONCEPT_ID, FSN from CONCEPTS where CONCEPT_ID in (%s)" % (conceptId)
#    cursor = connection_snomed.cursor()
#    cursor.execute(sql)
#    (cid, fsn) = cursor.fetchone()
#    return fsn

#Concept class ids:
#  1 = Body structure (body structure)
#  2 = Clinical finding (finding)
#  3 = Context-dependent categories (context-dependent category)
#  4 = Environments and geographical locations (environment / location)
#  5 = Events (event)
#  6 = Linkage concept (linkage concept)
#  7 = Observable entity (observable entity)
#  8 = Organism (organism)
#  9 = Pharmaceutical / biologic product (product)
#  10 = Physical force (physical force)
#  11 = Physical object (physical object)
#  12 = Procedure (procedure)
#  13 = Qualifier value (qualifier value)
#  14 = SNOMED_CT
#  15 = Social context (social concept)
#  16 = Special concept (special concept)
#  17 = Specimen (specimen)
#  18 = Staging and scales (staging scale)
#  19 = Substance (substance)

#def conceptClass(conceptId):
#    sql = "select CONCEPT_ID, CLASS_ID from CONCEPT_CLASSES where CONCEPT_ID in (%s)" % (conceptId)
#    cursor = connection_snomed.cursor()
#    cursor.execute(sql)
#    (cid, clsid) = cursor.fetchone()
#    return clsid
    
